var DBFactory = require('../db/mysql_db');
var courseDao = module.exports;

courseDao.getCourseList = function(data, cb) {
    // var sql = 'select * from course where status = 1 ';
    // var sql_total = 'select count(*) as count from course where status = 1 ';
    // var arr = [];
    // if(data.id) {
    //     sql += ' and id = ? ';
    //     sql_total += ' and id = ? ';
    //     arr.push(data.id);
    // }
    // DBFactory.executeSql(sql_total, arr, 'getCourseListTotal', function(err, total) {
    //     if(err) return cb(err);
    //     arr.push(data.start);
    //     arr.push(data.size);
    //     sql += ' limit ?, ? ';
    //     DBFactory.executeSql(sql, arr, 'getCourseListData', function(e, result) {
    //         if(err) return cb(e);
    //         cb(null, {total: total[0].count, data: result});
    //     })
    // })
    var sql = !data.isAdmin ? 'select * from course where status = 1 ' : 'select * from course where 1';
    var arr = [];
    if(data.id) {
        sql += ' and id = ? ';
        arr.push(data.id);
    }
    DBFactory.executeSql(sql, arr, 'getCourseListData', function(err, result) {
        if(err) return cb(err);
        cb(null, {data: result});
    })
}

courseDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var courseInfo = {};
    ['id', 'course', 'spec', 'status'].forEach(function(c) {
        if(data[c] != undefined) courseInfo[c] = data[c];
    })
    var sql = 'replace into course set ? ';
    DBFactory.executeSql(sql, courseInfo, 'save', function(err, result) {
        if(err) return cb(err);
        cb(null, '添加成功！');
    })
}

courseDao.del = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'update course set status = 0 where id = ? ';
    var sql_sub  = 'update course_items set status = 0 where course_id = ? ';
    DBFactory.executeSql(sql, [data.id], 'del', function(err, result) {
        if(err) return cb(err);
        DBFactory.executeSql(sql_sub, [data.id], 'del', function(err, result) {
            if(err) return cb(err);
            cb(null, '下架课程成功！');
        })
    })
}

courseDao.getSubCourseList = function(data, cb) {
    var sql = 'select course_items.*, mechanism.mechanism_name, mechanism.mechanism_avatar, mechanism.status as m_status ' +
        'from course_items left join mechanism on course_items.mechanism_id = mechanism.id left join mechanism_position ' +
        'on mechanism.id = mechanism_position.mechanism_id where 1 ';
    var sqlTotal = 'select count(*) as count from course_items where 1 ';
    var arr = [];
    if(data.status) {
        sql += ' and course_items.status = ? ';
        sqlTotal += ' and status = ? ';
        arr.push(data.status);
    }
    if(data.course_id) {
        sql += ' and course_items.course_id = ? ';
        sqlTotal += ' and course_id = ? ';
        arr.push(data.course_id);
    }
    sql += ' order by course_items.mechanism_id ';
    DBFactory.executeSql(sqlTotal, arr, 'getSubCourseListTotal', function(err, total) {
        if(err) return cb(err);
        if(total[0].count == 0) return cb(null, {total:0});
        sql += ' limit ? , ? ';
        arr.push(data.start);
        arr.push(data.size);
        DBFactory.executeSql(sql, arr, 'getSubCourseList', function(e, result) {
            if(e) return cb(e);
            cb(null, {total: total[0].count, data: result});
        })
    })
}

courseDao.updateSubStatus = function(data, cb) {
    var sql = 'update course_items set status = ? where id = ? ';
    DBFactory.executeSql(sql, [data.status, data.id], 'updateSubStatus', function(e, result) {
        if(e) return cb(e);
        cb(null, '上下架成功！');
    })
}

function authMpId(data, cb) {
    var sql = 'select * from mechanism_position where id = ? and end_date > now() and mechanism_id = ? and course_id = ? ';
    DBFactory.executeSql(sql, [data.mp_id, data.mechanism_id, data.course_id], 'authMpId', function(e, result) {
        if(e) return cb(e);
        if(result.length == 0) return cb({err:'您的地址已经过期或您还未添加该课程的地址！', status: 401});
        cb(null, data);
    })
}
courseDao.saveSubCourse = function(data, cb) {
    if(!data) return cb(new ERR(500));
    doSaveSubCourse(data, cb);
}
function doSaveSubCourse(data, cb) {
    var sql = 'replace into course_items set ? ';
    var subCourse = {};
    var keys = ['id', 'course_id', 'sub_course', 'crowd', 'sex', 'pics', 'mechanism_id', 'mp_id'];
    keys.forEach(function(k) {
        if(data[k]) subCourse[k] = data[k];
    })
    DBFactory.executeSql(sql, subCourse, 'saveSubCourse', function(e, result) {
        if(e) return cb(e);
        data.sub_course_id = data.id ? data.id : result.insertId;
        courseDao.saveCostSpec(data, cb);
    })
}
courseDao.saveCostSpec = function(data, cb) {
    var spec_arr_edit = [];
    var spec_arr_add = [];
    for(var i=0; i<data.cost_spec_arr.length; i++) {
        var arr = [];
        var obj = data.cost_spec_arr[i];
        var keys = obj.id ? ['lvl', 'target_lvl', 'class_count', 'duration', 'price', 'id'] :
            ['lvl', 'target_lvl', 'class_count', 'duration', 'price'];
        arr.push(data.sub_course_id);
        keys.forEach(function(k) {
            arr.push(obj[k]);
        })
        if(obj.id) {
            spec_arr_edit.push(arr);
        } else {
            spec_arr_add.push(arr);
        }
    }
    var sql = 'replace into cost_spec(`sub_course_id`,`lvl`,`target_lvl`,`class_count`,`duration`,`price`, `id`) values ? ';
    if(spec_arr_edit.length > 0) {
        DBFactory.executeSql(sql, [spec_arr_edit], 'saveCostSpec 1', function(e) {
            if(e) console.log(e);
        })
    }
    if(spec_arr_add.length > 0) {
        var sql_add = 'insert into cost_spec(`sub_course_id`,`lvl`,`target_lvl`,`class_count`,`duration`,`price`) values ? ';
        DBFactory.executeSql(sql_add, [spec_arr_add], 'saveCostSpec 2', function(e) {
            if(e) console.log(e);
        })
    }
    cb(null, data);
}

courseDao.delCostSpec = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select id from mechanism left join course_items on mechanism.id = course_items.mechanism_id where ' +
        ' mechanism.openid = ? and course_items.id = ? ';
    DBFactory.executeSql(sql, [data.openid, data.sub_course_id], 'delCostSpec getMechanismId', function(e, result) {
        if(e) return cb(e);
        if(result.length == 0) return cb('无权限删除！');
        var delSql = 'delete from cost_spec where id = ? and sub_course_id = ? ';
        DBFactory.executeSql(delSql, [data.id, data.sub_course_id], 'delCostSpec', function(err, r) {
            if(err) return cb(err);
            cb(null, '删除成功！');
        })
    })
}

courseDao.manage = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select mechanism_position.address, course.course from mechanism_position left join course on ' +
        ' mechanism_position.course_id = course.id where mechanism_position.mechanism_id = ? group by mechanism_position.course_id ';
    DBFactory.executeSql(sql, [data.mechanism_id], 'manage', function(err, result) {
        if(err) return cb(err);
        cb(null, result);
    })
}

courseDao.getSubCourseById = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select ci.id, ci.sub_course, ci.crowd, cs.class_count, cs.price from cost_spec as cs ' +
        'left join course_items as ci on cs.sub_course_id = ci.id where ci.mechanism_id = ? and ci.course_id = ? ';
    DBFactory.executeSql(sql, [data.mechanism_id, data.cid], 'manage', function(err, result) {
        if(err) return cb(err);
        if(result.length == 0) return cb(null, {});
        var courseName = {};
        console.log(result);
        result.forEach(function(c) {
            if(!courseName[c.sub_course]) {
                courseName[c.sub_course] = 1;
            }
        })
        var courseList = [];
        for(var name in courseName) {
            var c = {};
            c['课程'] = name;
            c['价格'] = [];
            c['人群'] = [];
            var crowdObj = {};
            result.forEach(function(r) {
                if(r.sub_course == name) {
                    crowdObj[r.crowd] = 1;
                    c['价格'].push(r.class_count + '节 ' + r.price + '元');
                }
            })
            for(var k in crowdObj) {
                c['人群'].push(k);
            }
            courseList.push(c);
        }
        cb(null, courseList);
    })
}